package com.zf.mo.bootquartz;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;
import java.util.concurrent.Executor;

@Configuration
public class ScheduleConfig {
    @Autowired
    private DataSource dataSource;
    @Bean
    public Scheduler scheduler() throws Exception{
        Scheduler scheduler = schedulerFactoryBean().getScheduler();
        return scheduler;
    }
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws Exception{
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setSchedulerName("my_schedule");
        schedulerFactoryBean.setDataSource(dataSource);
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("application");
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        schedulerFactoryBean.setTaskExecutor(schedulePool());
        schedulerFactoryBean.setStartupDelay(10);
        return schedulerFactoryBean;
    }
    @Bean
    public Properties quartzProperties()throws Exception{
        PropertiesFactoryBean propertiesFactory = new PropertiesFactoryBean();
        propertiesFactory.setLocation(new ClassPathResource("/spring-quartz.properties"));
        propertiesFactory.afterPropertiesSet();
        return propertiesFactory.getObject();
    }
    @Bean
    public Executor schedulePool(){
        ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
        poolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        poolTaskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors());
        poolTaskExecutor.setQueueCapacity(Runtime.getRuntime().availableProcessors());
        return poolTaskExecutor;
    }

}
